<template>
	<div>
		<SelectUser :isRadio="isRadio" :isNeedSearch="true" :userList="transferList" :title="title"
			@search="handleSearchMember" @complete="submit" @getMore="getMember('more')" :total="totalMember" />
		<!-- 删除群成员 -->
		<Dialog class="deleted-dialog" :title="TUITranslateService.t(`TUIGroup.删除成员`)" :show="delDialogShow"
			:isH5="!isPC" :center="true" :isHeaderShow="isPC" @submit="handleManage(deletedUserList, 'remove')"
			@update:show="(e) => (delDialogShow = e)">
			<p v-if="deletedUserList.length === 1" class="delDialog-title">
				{{ TUITranslateService.t(`TUIGroup.确定从群聊中删除该成员？`) }}
			</p>
			<p v-if="deletedUserList.length > 1" class="delDialog-title">
				{{ TUITranslateService.t(`TUIGroup.确定从群聊中删除所选成员？`) }}
			</p>
		</Dialog>
	</div>
</template>

<script lang="ts" setup>
	import TUIChatEngine, {
		TUITranslateService,
		TUIStore,
		StoreName,
		TUIGroupService,
		TUIFriendService,
		TUIUserService
	} from "@tencentcloud/chat-uikit-engine";
	import Dialog from "../../common/Dialog/index.vue";
	import { TUIGlobal } from "@tencentcloud/universal-api";
	import { Toast, TOAST_TYPE } from "../../common/Toast/index";
	import { ref } from "../../../adapter-vue";
	import { isPC } from "../../../utils/env";
	import { IGroupMember } from "../../../interface";
	import SelectUser from "../../common/SelectUser/index.vue";
	import { onLoad, onShow } from "@dcloudio/uni-app";
	import { checkUserInfo } from "../../../utils/checkLogin";
	import CallkitPluginServer from "../../../plugins/extension-server/callkit";
	const callkit = new CallkitPluginServer()
	
	const groupID = ref('')
	const title = ref('')
	let type = ref('')
	let isRadio = ref(false)
	//拨打电话类型
	let callType=ref('')
	//我的好友列表
	let friendList = ref<Array<IGroupMember>>([]);
	//搜索记录
	let searchList = ref<Array<IGroupMember>>([]);
	//群成员
	const memberList = ref<Array<IGroupMember>>([]);
	//所有群成员id数组
	const groupMemberIdList : any = ref([])
	//当前显示长度
	const totalMember = ref(0)
	//当前展示的成员列表
	const transferList = ref<Array<IGroupMember>>([]);
	//当前登录用户信息
	const userInfo = ref({});
	//当前被删除的群用户
	const deletedUserList = ref<Array<IGroupMember>>([]);
	//是否显示移除群用户的弹窗
	const delDialogShow = ref(false);
	let source = ref('')
	onLoad((options : any) => {
		callType.value=options.callType||''
		groupID.value = options.GroupID
		title.value = options.title
		type.value = options.type
		memberList.value = options.memberList ? JSON.parse(options.memberList) : []
		TUIStore.watch(StoreName.CUSTOM, {
			IMuserInfo: (data : any) => {
				if (data) {
					userInfo.value = data
					TUIGroupService.getGroupProfile({
						groupID: groupID.value,
					}).then((res) => {
						if (type.value === 'addAdmin') {
							isRadio.value = true
							toggleMask()
						} else {
							getMember()
							totalMember.value = res.data.group.memberCount - 1
						}

					}).catch((error) => {
						console.log(error, "异常")
					})
				}
			}
		})
	})
	onShow(() => {
		TUIStore.watch(StoreName.CUSTOM, {
			IMuserInfo: (data : any) => {
				if (data) {
					userInfo.value=data
					source.value = data.source
					checkUserInfo()
				}

			}
		})
	})


	const getMember = (type ?: string) => {
		const options = {
			groupID: groupID.value,
			count: 100,
			offset: type && type === "more" ? memberList.value.length : 0,
		};
		TUIGroupService.getGroupMemberList(options).then((res : any) => {
			if (type && type === "more") {
				memberList.value = [...memberList.value, ...res.data.memberList];
			} else {
				memberList.value = res.data.memberList;
			}
			groupMemberIdList.value = memberList.value.map(
				(item : any) => item.userID
			);
			console.log(memberList.value, "memberList.value ")
			toggleMask()
		});

	};
	const submit = (userList : any) => {
		if (!userList.length) {
			return handleCancel()
		}
		// 进行成员移除等等相关操作
		if (type.value === "remove") {
			deletedUserList.value = userList;
			delDialogShow.value = !delDialogShow.value;
		} else {
			handleManage(userList, type.value);
		}
	};

	const handleManage = (userList : any, type : any) => {
		const userIDList : any = [];
		userList.map((item : any) => {
			userIDList.push(item.userID);
			return item;
		});
		switch (type) {
			case "add":
				addMember(userIDList);
				break;
			case "remove":
				deleteGroupMember(userIDList);
				break;
			case "addAdmin":
				handleAdmin(userList[0]);
				break;
			case "callKit":
				handleCallKit(userIDList);
				break;
			default:
				break;
		}
	};
	const handleAdmin = async (user : any) => {
		let role = TUIChatEngine.TYPES.GRP_MBR_ROLE_ADMIN;
		const options : any = {
			groupID: groupID.value,
			userID: user.userID,
			role,
		};
		await TUIGroupService.setGroupMemberRole(options);
		uni.navigateBack()
	};
	const addMember = (userIDList : any) => {
		const options : any = {
			groupID: groupID.value,
			userIDList,
		};
		TUIGroupService.addGroupMember(options).then(res => {
			handleCancel()
		}).catch(res => {
			console.log(res, "异常的")
		});


	};
	const handleCallKit=(userIDList)=>{
		if(userIDList.length>8){
			uni.showToast({
				title: "最多支持九人通话",
				icon: "none",
			})
			return
		}
		TUIGlobal?.navigateBack();
		callkit.setCallExtension({ userIDList: userIDList, type: callType.value,groupID:groupID.value })
	}
	const deleteGroupMember = (userIDList : any) => {
		const options : any = {
			groupID: groupID.value,
			userIDList,
			reason: "",
		};
		TUIGroupService.deleteGroupMember(options).then(res => {
			handleCancel()
		});;
	};
	const handleCancel = () => {
		TUIGlobal?.navigateBack();
	}
	const handleSearchMember = async (value : string) => {
		let imResponse : any = {};
		let imMemberResponse : any = {};
		const options : any = {
			groupID: groupID.value,
			userIDList: [value],
		};
		//添加成员搜索  在所有用户里面搜索
		if (type.value === "add") {
			try {
				//清空搜索文字 保留我的好友以及搜索记录
				if (value === '') {
					//排除了我的好友的返回结果
					let arr : any = []
					if (searchList.value.length) {
						//筛选搜索到的用户在好友列表里面 就不加入数组
						arr = friendList.value.filter((item : any) => item.userID === searchList.value[0]?.userID);
						arr = arr.length === 0 ? searchList.value : []
					}
					transferList.value = friendList.value.concat(arr);
					friendList.value = transferList.value
					return
				}
				//所有用户里面筛选
				let imMemberResponse = await TUIUserService.getUserProfile({ userIDList: [value + '_' + source.value] });
				//没有搜索到
				if (!imMemberResponse.data.length) {
					return transferList.value = []
				}
				//搜索到的用户已经在群里
				if (groupMemberIdList.value.indexOf(imMemberResponse.data[0].userID) !== -1) {
					imMemberResponse.data[0].isDisabled = true
				}
				//搜索到了
				searchList.value = imMemberResponse.data
				//显示搜索到的
				transferList.value = imMemberResponse.data
			} catch (error : any) {
				if (error.code === 3003) {
					uni.showToast({
						title: "聊天账号已在其他设备登录",
						icon: "none",
					})
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/tabbar/index'
						})
					}, 1000)
					return null
				}

				uni.showToast({
					title: "查找失败：" + error?.message,
					icon: "none",
					duration: 1000,
				});
			}
		} else if (type.value === "remove" || type.value === "addAdmin"||type.value === "callKit") {
			//新增管理员和移除成员  在群里用户搜索
			try {
				if (value === '') {
					transferList.value = memberList.value
					return
				}
				let imResponse = { data: { memberList: [] } }
				if (type.value === "remove") {
					imResponse = await TUIGroupService.getGroupMemberProfile(options)
				} else {
					console.log(memberList.value, "当前用户成员")
					imResponse.data.memberList = memberList.value.filter(item => item.userID === value)
				}
				if (imResponse.data.memberList.length === 0) {
					transferList.value = []
				}
				transferList.value = imResponse?.data?.memberList
			} catch (error : any) {
				const message = TUITranslateService.t("TUIGroup.该用户不存在");
				Toast({
					message,
					type: TOAST_TYPE.ERROR,
				});
			}
		}
		totalMember.value = transferList.value.length
	};


	const toggleMask = async () => {
		switch (type.value) {
			case "add":
				transferList.value = await getFriendList();
				friendList.value = transferList.value
				console.log(transferList.value, "transferList.value")
				break;
			case "remove":
				transferList.value = memberList.value.filter(
					(item : any) => item.userID !== userInfo.value.txUserId
				);
				break;
			case "addAdmin":
				transferList.value = memberList.value
				totalMember.value = memberList.value.length
				break;
			case "callKit":
				transferList.value = memberList.value.filter(
					(item : any) => item.userID !== userInfo.value.txUserId
				);
				break;
			default:
				break;
		}

	};

	const getFriendList = async () => {

		//我的好友列表
		const imResponse = await TUIFriendService.getFriendList();
		//在群里的好友禁用
		const friendList = imResponse.data.map((item : any) => {
			if (item.profile && groupMemberIdList.value.indexOf(item.profile.userID) > -1) {
				item.profile.isDisabled = true
			} else {
				item.profile.isDisabled = false
			}
			return item.profile
		});
		//排除自己
		totalMember.value = friendList.length - 1
		//排除自己
		return friendList.filter(
			(item : any) => !(userInfo.value.userID === item.userID)
		);
	};
</script>

<style lang="scss" scoped>
	@import url("../../../assets/styles/common.scss");

	page {
		background: #fff;
	}

	.member {
		flex: 1;
		background: #ffffff;

		.list {
			display: flex;
			flex-direction: column;
			background: #f4f5f9;
			padding-top: 22px;

			&-uniapp {
				background: none;
			}

			&-item {
				padding: 13px;
				display: flex;
				justify-content: space-between;
				align-items: center;
				background: #ffffff;
				font-size: 14px;
				overflow: hidden;
				cursor: pointer;

				&:hover {
					background: #f1f2f6;
				}

				.aside {
					display: flex;
					align-items: center;
					width: 100%;
					overflow: hidden;

					.name {
						margin-left: 8px;
						font-weight: 400;
						font-size: 14px;
						color: #000000;
						flex: 1;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
				}
			}
		}
	}

	.avatar {
		width: 36px;
		height: 36px;
		border-radius: 100%;
	}

	.edit-h5 {
		// position: fixed;
		width: 100%;
		height: 100%;

		// top: 0;
		// left: 0;
		// background: rgba(0, 0, 0, 0.5);
		// display: flex;
		// align-items: flex-end;
		// z-index: 1;
		.main {
			flex: 1;
		}

		&-header {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.close {
				font-family: PingFangSC-Regular;
				font-weight: 400;
				font-size: 18px;
				color: #3370ff;
				letter-spacing: 0;
				line-height: 27px;
			}
		}

		&-footer {
			display: flex;

			.btn {
				flex: 1;
				border: none;
				background: #147aff;
				border-radius: 5px;
				font-family: PingFangSC-Regular;
				font-weight: 400;
				font-size: 16px;
				color: #ffffff;
				letter-spacing: 0;
				line-height: 27px;
				padding: 8px 0;

				&:disabled {
					opacity: 0.3;
				}
			}
		}
	}

	.label {
		padding: 4rpx 16rpx;
		background: #FAB221;
		font-size: 24rpx;
		color: #fff;
		margin-left: 10rpx;
		border-radius: 10rpx;
	}

	.label01 {
		background: #00D107 !important;
	}
</style>